<!--
 * @Author: ccr ccr888888
 * @Date: 2022-11-14 14:03:25
 * @LastEditors: ZJC
 * @LastEditTime: 2023-07-27 13:39:36
 * @FilePath: \master-admin\vue-admin\src\views\editor\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editor"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      class="editor"
      :style="'height: ' + height + 'px; overflow-y: hidden'"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="onCreated"
      @onChange="onChange"
      @input="(e) => $emit('update:value', e.trim())"
    />
  </div>
</template>
<script>
import Vue from "vue";

import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import toolbarConfig from "./toolbarConfig";
import editorConfig from "./editorConfig";
import { initComponent } from "./initComponent.js";
initComponent();

export default {
  props: {
    value: {
      type: String,
    },
    height: {
      type: [Number, String],
      default: 360,
    },
  },

  components: { Editor, Toolbar },
  data() {
    return {
      editor: null,
      toolbarConfig: toolbarConfig,
      editorConfig: editorConfig,
      mode: "default", // default or 'simple'
    };
  },

  updated() {
    // const toolbar = DomEditor.getToolbar(this.editor);
    // const curToolbarConfig = toolbar.getConfig();
  },
  watch: {
    value(e) {
      let html = this.editor.getHtml();
      if (e != html) {
        this.editor.setHtml(e);
      }
    },
  },
  created() {},
  mounted() {
    // 模拟 ajax 请求，异步渲染编辑器
    // setTimeout(() => {
    //   this.html = "<p>模拟 Ajax 异步设置内容 HTML</p>";
    // }, 1500);
  },
  methods: {
    onCreated(editor) {
      // debugger
      this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
      this.editor.setHtml(this.value);
      // console.log(this.editor.getAllMenuKeys());
    },
    onChange(editor) {
      let html = editor.getHtml();
      let text = editor.getText();
      if (html == "<p><br></p>") {
        this.$emit("input", "");
      } else {
        this.$emit("input", html);
      }
    },
  },
  beforeDestroy() {
    const editor = this.editor;
    if (editor == null) return;
    editor.destroy(); // 组件销毁时，及时销毁编辑器
  },
};
</script>
<style lang="scss" scoped>
@import "~@wangeditor/editor/dist/css/style.css";
</style>
